package com.core.enums.serializer;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.core.enums.StringEnum;

import java.lang.reflect.Type;

/**
 * value值为String类型的枚举序列化类
 *
 */
public class StringEnumSerializer implements ObjectSerializer, ObjectDeserializer {
    @Override
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        String value = parser.parseObject(String.class);
        if (value == null) {
            return null;
        }
        T result = StringEnum.of(((Class<T>) type), value);
        return result;
    }

    @Override
    public int getFastMatchToken() {
        return 0;
    }

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) {
        if (object == null) {
            serializer.getWriter().writeNull();
            return;
        }
        SerializeWriter out = serializer.getWriter();
        StringEnum t = (StringEnum) object;
        String json = t.getValue();
        if (json != null) {
            out.write("\"" + json + "\"");
        } else {
            out.writeNull();
        }
    }
}
